package Concurrent;

import org.junit.internal.runners.statements.RunAfters;

import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description：
 * Author: zhangc
 * Date：2017/9/29 19:33
 */
public class BlockingProducerConsumer {

    private static BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(20);
    private static AtomicInteger integer = new AtomicInteger(0);

    public static void produce() throws InterruptedException {
        int increment = integer.getAndIncrement();
        queue.put(increment);
        System.out.println(Thread.currentThread().getName() + ":" + "生产者生产了一个产品：" + increment);
    }

    public static void consumer() throws InterruptedException {
        Integer take = queue.take();
        System.out.println(Thread.currentThread().getName() + ":" + "消费者消费了一个产品：" + take);
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10, new ThreadFactory());
        for (int i = 0; i < 10; i++) {
            service.execute(new ProducerBlocking());
            if (i % 4 == 3)
                service.execute(new ConsumerBlocking());
        }
    }

}

class ProducerBlocking implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            try {
                BlockingProducerConsumer.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class ConsumerBlocking implements Runnable {

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            try {
                BlockingProducerConsumer.consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
